package org.cn.lennon.mybatis.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

import org.cn.lennon.mybatis.config.Configuration;
import org.cn.lennon.mybatis.config.MapperStatment;
import org.cn.lennon.mybatis.executors.OperationType;
import org.cn.lennon.mybatis.session.impl.DefaultSqlSession;

public class MapperProxy implements InvocationHandler {

	private DefaultSqlSession defaultSqlSession;
	private Configuration configuration;

	public MapperProxy(DefaultSqlSession defaultSqlSession, Configuration configuration) {
		super();
		this.defaultSqlSession = defaultSqlSession;
		this.configuration = configuration;
	}

	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		String stamentId = method.getDeclaringClass().getName() + "." + method.getName();
		MapperStatment mapperStatment = configuration.mapperRegister.getSqlMapperStatment(stamentId);
		if (mapperStatment != null) {
			if(OperationType.SELECT.equals(mapperStatment.getType())) {
				return defaultSqlSession.selectOne(stamentId, args);
			} else if(OperationType.UPDATE.equals(mapperStatment.getType())) {
				return defaultSqlSession.update(stamentId, args);
			} else if(OperationType.INSERT.equals(mapperStatment.getType())) {
				return defaultSqlSession.insert(stamentId, args);
			}else if(OperationType.DELETE.equals(mapperStatment.getType())) {
				return defaultSqlSession.delete(stamentId, args);
			}
				
		}
		return method.invoke(proxy, args);
	}

}
